import util from "../util/util";
import Taro from "@tarojs/taro";
import { getGlobal } from "./globalData";

const interceptor = function(chain) {
  const p = chain.requestParams;

  let contentType;
  if (p.header) {
    contentType = p.header["content-type"];
  }
  // 请求携带base64加密的token
  let userIfo = getGlobal("userInfo");
  if (userIfo) {
    p.header = {
      token: userIfo.token,
      "content-type": contentType
    };
  }
  return chain.proceed(p).then(res => {
    const { data } = res;
    // 服务端返回错误则toast提示
    if (!data.success) {
      Taro.showToast({ title: data.msg, icon: "none" });
    }
    return res;
  });
};
Taro.addInterceptor(interceptor);
export default class Api {
  // 服务器地址
  static serverHost = "https://www.chaoyer.com";

  // 登录接口
  static async login(user) {
    return await Taro.request({
      url: `${this.serverHost}/csy/user/wx/login`,
      method: "POST",
      data: user
    });
  }

  // 获取微信的session
  static async codeSession(code) {
    return await Taro.request({
      url: `${this.serverHost}/csy/user/wx/session?code=${code}`
    });
  }

  // 文章列表
  static async docList(keyword, sortType, pageNo, pageSize) {
    return await Taro.request({
      url: `${
        this.serverHost
      }/csy/note/list?keyword=${keyword}&pageSize=${pageSize}&pageNo=${pageNo}&sortType=${sortType}`
    });
  }

  // 文章详情
  static async docDetail(id) {
    return await Taro.request({
      url: `${this.serverHost}/csy/note/detail?noteId=${id}`
    });
  }

  // 分类列表
  static async categoryList() {
    return await Taro.request({
      url: `${this.serverHost}/csy/category/list`
    });
  }

  // 阅读历史列表
  static async readRecordsList(pageNo, pageSize) {
    return await Taro.request({
      url: `${
        this.serverHost
      }/csy/user/readRecords?pageSize=${pageSize}&pageNo=${pageNo}`
    });
  }

  // 创建收藏夹
  static async createSubject(subject) {
    return await Taro.request({
      url: `${this.serverHost}/csy/subject/create`,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: util.json2Form(subject)
    });
  }

  // 获取个人的收藏夹，不分页
  static async personSubject(noteId, noteType) {
    return await Taro.request({
      url: `${
        this.serverHost
      }/csy/subject/list?noteId=${noteId}&noteType=${noteType}&type=1`
    });
  }

  // 收藏添加/删除
  static async operateSubjetNote(operate) {
    return await Taro.request({
      url: `${this.serverHost}/csy/subject/note/operate`,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: util.json2Form(operate)
    });
  }

  // 收藏夹文章列表
  static async subjectArticles(subjectId, pageNo, pageSize) {
    return await Taro.request({
      url: `${
        this.serverHost
      }/csy/subject/notes?pageSize=${pageSize}&pageNo=${pageNo}&subjectId=${subjectId}`
    });
  }
}
